package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.User;
import com.itheima.thread.TokenThreadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author YangJiaHao
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //鉴权
        //1.获取请求头上的token信息
        String token = request.getHeader("AuthorizationUser");
        if (StringUtils.isEmpty(token)){
            throw new RuntimeException("token不能为空");
        }
        //2.拿token到Redis里去查
        String userJsonInfo = redisTemplate.opsForValue().get("user_token:"+token);
        if (StringUtils.isEmpty(userJsonInfo)){
            throw new RuntimeException("token已失效");
        }

        //把用户信息写入到ThreadLocal里面
        User user = JSON.parseObject(userJsonInfo, User.class);
        if (user==null){
            throw new RuntimeException("token已失效");
        }
        TokenThreadUtils.setThreadLocal(user);

        System.out.println("token校验成功");
        redisTemplate.opsForValue().set("user_token:"+token, JSON.toJSONString(user));
        return true;
    }
}
